<template>
	<xn-form-container
		:title="formData.id ? '编辑模块' : '增加模块'"
		:width="550"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="委托公司" name="companyCode">
				<CompanySelect v-model:value="formData.companyCode" />
			</a-form-item>
			<a-form-item label="产品编号" name="productCode">
				<a-input v-model:value="formData.productCode" placeholder="请输入" allow-clear />
			</a-form-item>
			<a-form-item label="产品名称" name="productName">
				<a-input v-model:value="formData.productName" placeholder="请输入" allow-clear />
			</a-form-item>
			<a-form-item label="产品描述" name="productDescription">
				<a-input v-model:value="formData.productDescription" placeholder="请输入" allow-clear />
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button class="xn-mr8" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup>
	import { required } from '@/utils/formRules'
	import productApi from '@/api/tjzy/product/productApi'
	import CompanySelect from '@/components/Tjzy/Company/index.vue'
	// 默认是关闭状态
	const visible = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	// 表单数据
	const formData = ref({})

	// 打开抽屉
	const onOpen = (record) => {
		visible.value = true
		formData.value = {
			sortCode: 99
		}
		console.log(record)
		if (record) {
			formData.value = Object.assign({}, record)
		}
	}
	// 关闭抽屉
	const onClose = () => {
		formRef.value.resetFields()
		visible.value = false
	}

	// 默认要校验的
	const formRules = {
		companyCode: [required('请选择所属公司')],
		productCode: [required('请输入产品编号')],
		productName: [required('请输入产品名称')],
		productDescription: [required('请输入产品描述')]
	}

	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				console.log(formData.value)
				if (formData.value.id) {
					productApi.editProduct(formData.value).then(() => {
						onClose()
						emit('successful')
					})
				} else {
					productApi.addProduct(formData.value).then(() => {
						onClose()
						emit('successful')
					})
				}
			})
			.catch(() => {})
	}

	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})
</script>
